package com.ruoyi.web.controller.applet;

import com.alibaba.fastjson.JSON;
import com.ruoyi.applet.product.domain.Product;
import com.ruoyi.applet.product.domain.ProductCategories;
import com.ruoyi.applet.product.service.IProductCategoriesService;
import com.ruoyi.applet.product.service.IProductService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 产品Controller
 * @author ruoyi
 * @date 2024-11-20
 */
@Controller
@RequestMapping("/applet/product")
public class ProductController extends BaseController {
    
    private final String prefix = "applet/product";
    
    private static final String FILE_DELIMETER = ",";
    
    @Resource
    private IProductService productService;
    @Resource
    private IProductCategoriesService productCategoriesService;
    @Resource
    private ServerConfig serverConfig;
    
    @RequiresPermissions("applet:product:view")
    @GetMapping()
    public String product(ModelMap mmap) {
        ProductCategories productCategories = new ProductCategories();
        productCategories.setStatus(1);
        List<ProductCategories> productCategoriesList = productCategoriesService.selectProductCategoriesList(productCategories);
        mmap.put("productCategoriesList", productCategoriesList);
        return prefix + "/product";
    }
    
    /**
     * 查询产品列表
     */
    @RequiresPermissions("applet:product:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Product product) {
        startPage();
        List<Product> list = productService.selectProductList(product);
        return getDataTable(list);
    }
    
    /**
     * 新增产品
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        ProductCategories productCategories = new ProductCategories();
        productCategories.setStatus(1);
        List<ProductCategories> productCategoriesList = productCategoriesService.selectProductCategoriesList(productCategories);
        mmap.put("productCategoriesList", productCategoriesList);
        return prefix + "/add";
    }
    
    /**
     * 新增保存产品
     */
    @RequiresPermissions("applet:product:add")
    @Log(title = "产品", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Product product) {
        return toAjax(productService.insertProduct(product));
    }
    
    /**
     * 修改产品
     */
    @RequiresPermissions("applet:product:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        ProductCategories productCategories = new ProductCategories();
        productCategories.setStatus(1);
        List<ProductCategories> productCategoriesList = productCategoriesService.selectProductCategoriesList(productCategories);
        mmap.put("productCategoriesList", productCategoriesList);
        Product product = productService.selectProductById(id);
        mmap.put("product", product);
        List<String> list = JSON.parseArray(product.getPicturesPath(), String.class);
        mmap.put("pictures", list);
        return prefix + "/edit";
    }
    
    /**
     * 修改保存产品
     */
    @RequiresPermissions("applet:product:edit")
    @Log(title = "产品", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Product product) {
        return toAjax(productService.updateProduct(product));
    }
    
    /**
     * 删除产品
     */
    @RequiresPermissions("applet:product:remove")
    @Log(title = "产品", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(productService.deleteProductByIds(ids));
    }
    
    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath() + "/applet/product";
            List<String> urls = new ArrayList<>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", JSON.toJSONString(urls));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath() + "/applet/product";
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
